/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.base.manager.impl;

import com.xy.biz.base.dao.RegionDao;
import com.xy.biz.base.domain.dto.RegionDTO;
import com.xy.biz.base.domain.query.RegionQuery;
import com.xy.biz.base.manager.RegionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 
 * 
 * @author zsp
 * @date 2020-8-26
 */
@Service
public class RegionManagerImpl implements RegionManager {

	//local cache
	private final ConcurrentMap<String, List<RegionDTO>> cache = new ConcurrentHashMap<>(4096);

	@Autowired
	private RegionDao regionDao;
	
	@Override
	public List<RegionDTO> listRegion(RegionQuery query) {
		Long parentRegionId = query.getParentRegionId();
		String level = query.getOneLevel();
		if(null == level) {
			level = query.getTowLevel();
		}
		String cacheKey = (parentRegionId == null ? -1L : parentRegionId) + "-" + (level == null ? "" : level);
		List<RegionDTO> list = cache.computeIfAbsent(cacheKey, (e) -> regionDao.listRegion(query));
		if(!CollectionUtils.isEmpty(list)) {
			if(query.getOffset() == 0 && query.getRows() >= list.size()) {
				return list;
			} else if(query.getOffset() < list.size()) {
				int endIndex = query.getOffset() + query.getRows();
				endIndex = endIndex >= list.size() ? list.size() - 1 : endIndex;
				return list.subList(query.getOffset(), endIndex);
			} else {
				return Collections.emptyList();
			}
		}
		return list;
	}

	/**
	 * 查找多个
	 *
	 * @param collection 查找条件
	 */
	@Override
	public List<RegionDTO> listRegionById(Collection<Long> collection) {
		return regionDao.listRegionById(collection);
	}

}
